package com.lsl.gulimall.ware.service.impl;

import com.lsl.common.constant.WareConstant;
import com.lsl.gulimall.ware.entity.WmsPurchaseDetailEntity;
import com.lsl.gulimall.ware.service.WmsPurchaseDetailService;
import com.lsl.gulimall.ware.service.WmsWareSkuService;
import com.lsl.gulimall.ware.vo.MergeVo;
import com.lsl.gulimall.ware.vo.PurchaseDoneVo;
import com.lsl.gulimall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lsl.common.utils.PageUtils;
import com.lsl.common.utils.Query;

import com.lsl.gulimall.ware.dao.WmsPurchaseDao;
import com.lsl.gulimall.ware.entity.WmsPurchaseEntity;
import com.lsl.gulimall.ware.service.WmsPurchaseService;

import javax.validation.constraints.NotNull;


@Service("wmsPurchaseService")
public class WmsPurchaseServiceImpl extends ServiceImpl<WmsPurchaseDao, WmsPurchaseEntity> implements WmsPurchaseService {
    @Autowired
    WmsPurchaseService wmsPurchaseService;

    @Autowired
    WmsPurchaseDetailService wmsPurchaseDetailService;
    @Autowired
    WmsWareSkuService    wmsWareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<WmsPurchaseEntity> page = this.page(
                new Query<WmsPurchaseEntity>().getPage(params),
                new QueryWrapper<WmsPurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryUnreceiveList(Map<String, Object> params) {
        QueryWrapper<WmsPurchaseEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", '0').or().eq("status", '1');

        IPage<WmsPurchaseEntity> page = this.page(
                new Query<WmsPurchaseEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public void mergePurchase(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        List<Long> mergeVoItems = mergeVo.getItems();
        if (purchaseId == null) {
            WmsPurchaseEntity wmsPurchaseEntity = new WmsPurchaseEntity();
            wmsPurchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            wmsPurchaseEntity.setCreateTime(new Date());
            wmsPurchaseEntity.setUpdateTime(new Date());
            wmsPurchaseService.save(wmsPurchaseEntity);

            purchaseId = wmsPurchaseEntity.getId();
        }
        //TODO 确认采购单状态是0,1才可以合并
        WmsPurchaseEntity purchaseEntity = wmsPurchaseService.getById(purchaseId);
        if (purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || purchaseEntity.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
            Long finalPurchaseId = purchaseId;
            List<WmsPurchaseDetailEntity> wmsPurchaseDetailEntities = mergeVoItems.stream().map(
                    (item) ->
                    {
                        WmsPurchaseDetailEntity serviceById = wmsPurchaseDetailService.getById(item);
                        serviceById.setId(item);
                        serviceById.setStatus(WareConstant.PurchaseDetailStatusEnum.ASSIGNED.getCode());
                        serviceById.setPurchaseId(finalPurchaseId);
                        return serviceById;
                    }
            ).collect(Collectors.toList());
            wmsPurchaseDetailService.updateBatchById(wmsPurchaseDetailEntities);
        }
    }

    @Override
    public void receivedPurchase(List<Long> ids) {
        List<WmsPurchaseEntity> purchaseEntityList = ids.stream().map(
                (item) -> {
                    WmsPurchaseEntity wmsPurchaseServiceById = wmsPurchaseService.getById(item);
                    return wmsPurchaseServiceById;
                }
        ).filter(
                (purchase) ->
                {
                    if (purchase.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || purchase.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                        return true;
                    } else {
                        return false;
                    }
                }
        ).map(item -> {
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        this.updateBatchById(purchaseEntityList);

        for (WmsPurchaseEntity wmsPurchaseEntity : purchaseEntityList) {
            QueryWrapper<WmsPurchaseDetailEntity> detailEntityQueryWrapper = new QueryWrapper<>();
            detailEntityQueryWrapper.eq("purchase_id", wmsPurchaseEntity.getId());

            List<WmsPurchaseDetailEntity> wmsPurchaseDetailEntities = wmsPurchaseDetailService.list(detailEntityQueryWrapper);
            List<WmsPurchaseDetailEntity> purchaseDetailEntities = wmsPurchaseDetailEntities.stream().map(
                    (item) ->
                    {
                        WmsPurchaseDetailEntity wmsPurchaseDetailEntity = new WmsPurchaseDetailEntity();
                        BeanUtils.copyProperties(item, wmsPurchaseDetailEntity);
                        wmsPurchaseDetailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.BUYING.getCode());
                        return wmsPurchaseDetailEntity;
                    }

            ).collect(Collectors.toList());
            wmsPurchaseDetailService.updateBatchById(purchaseDetailEntities);
        }
    }

    @Override
    public void donePurchase(PurchaseDoneVo purchaseDoneVo) {
        Long id = purchaseDoneVo.getId();

        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        ArrayList<WmsPurchaseDetailEntity> wmsPurchaseDetailEntities = new ArrayList<>();
        Boolean flag = true;
        for (PurchaseItemDoneVo purchaseDetail : items) {
            WmsPurchaseDetailEntity wmsPurchaseDetailEntity = new WmsPurchaseDetailEntity();
            Long itemId = purchaseDetail.getItemId();
            if(purchaseDetail.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()){
             flag=false;
             wmsPurchaseDetailEntity.setStatus(purchaseDetail.getStatus());
            }else{
                wmsPurchaseDetailEntity.setStatus(purchaseDetail.getStatus());
                WmsPurchaseDetailEntity purchaseDetailServiceById = wmsPurchaseDetailService.getById(itemId);
                //采购成功 库存数加上对应的采购数
                try {
                    wmsWareSkuService.addStock(purchaseDetailServiceById.getWareId(),purchaseDetailServiceById.getSkuId(),purchaseDetailServiceById.getSkuNum());
                }catch (Exception e){
                    log.error(e.getMessage());
                }

            }
            wmsPurchaseDetailEntity.setId(purchaseDetail.getItemId());
            wmsPurchaseDetailEntity.setPurchaseId(id);
            wmsPurchaseDetailEntities.add(wmsPurchaseDetailEntity);
        }
        wmsPurchaseDetailService.updateBatchById(wmsPurchaseDetailEntities);

        //1、改变采购单状态
        WmsPurchaseEntity purchaseEntity = new WmsPurchaseEntity();
        purchaseEntity.setId(id);
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }
}